package com.chaowen.util;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.chaowen.config.Config;
import com.chaowen.model.UserInfo;

import android.net.wifi.WifiManager;
import android.os.Handler;

public class AnswerClient implements Runnable{
	
	private WifiManager.MulticastLock lock;
	private Handler handler;
	private DatagramPacket receive;
	private DatagramSocket server;
	private List<String> paperNameList = new ArrayList<String>();
	public AnswerClient(WifiManager manager,Handler handler) {
		this.lock= manager.createMulticastLock("UDPwifi"); 
		this.handler = handler;
	}
	
	private String[] getDate() throws Exception{
		receive = new DatagramPacket(new byte[1024], 1024);
        server = new DatagramSocket(Config.answerCastPort);
		lock.acquire();
        server.receive(receive);
        byte[] recvByte = Arrays.copyOfRange(receive.getData(), 0,
                receive.getLength());
        String msg = new String(recvByte);
        System.out.println("msg-=-=-=--->"+msg);
        String msgs[] = msg.split(":");
        this.lock.release();
        server.close();
		return msgs;
	}
	
	private void getClient(String[] msgs) throws Exception{
        if(msgs[0].equals("startAnswer")) {
        	Config.singleStart = Integer.parseInt(msgs[1]);
        	Config.singleEnd = Integer.parseInt(msgs[2]);
        	Config.multipleStart = Integer.parseInt(msgs[3]);
        	Config.multipleEnd = Integer.parseInt(msgs[4]);
        	Config.digitalStart = Integer.parseInt(msgs[5]);
        	Config.digitalEnd = Integer.parseInt(msgs[6]);
        	Config.endNumbers = Math.max(Math.max(Config.singleEnd, Config.multipleEnd), Config.digitalEnd);
        	Config.startNumbers = Math.min(Math.min(Config.singleStart, Config.multipleStart), Config.digitalStart);
        	System.out.println("aaaConfig.startNumbers: "+Config.startNumbers+"   "+Config.endNumbers);
        	if(Config.startNumbers==0&&Config.endNumbers>0) Config.startNumbers++;
        	System.out.println("Config.startNumbers: "+Config.startNumbers);
         	handler.sendEmptyMessage(28);
        }
	}
	
	@Override
	public void run() {
		try {
			while(UserInfo.isSign) {
				String strs[] = getDate();
				if(!paperNameList.contains(strs[7])) {
					Config.paperName = strs[7];
					paperNameList.add(Config.paperName);
					getClient(strs);
					System.out.println("书卷类型-----》"+Config.paperName);
				}
				System.out.println("UserInfo.isSign^^^^: "+UserInfo.isSign);
				Thread.sleep(1000);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}	
